package vn.co.thn.web.demo_app_engine.api;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import vn.co.thn.web.demo_app_engine.PMF;
import vn.co.thn.web.demo_app_engine.bean.BeanBase;
import vn.co.thn.web.demo_app_engine.bean.UrlUpload;
import vn.co.thn.web.demo_app_engine.jpa.Category;
import vn.co.thn.web.demo_app_engine.json_object.CategoryList;
import vn.co.thn.web.demo_app_engine.model.CategoryModel;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gson.Gson;

@Path("/category")
public class ApiCategory {
	@SuppressWarnings("unchecked")
	@Path("/list")
	@POST
	@Produces("application/json")
	public String list() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Category> list = new ArrayList<Category>();
		Query q = pm.newQuery(Category.class);
		q.setFilter("Delete == 1");
		list = (List<Category>) q.execute();
		CategoryList lst=new CategoryList();
		lst.setLst(list);
		return new Gson().toJson(lst);
	}

	@Path("/url_upload")
	@Produces("application/json")
	@GET
	public String urlupload() {
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		String url=blobstoreService.createUploadUrl("/api/category/add");
		UrlUpload urlUpload=new UrlUpload();
		urlUpload.setUrl(url);
		return  new Gson().toJson(urlUpload);
		
	}

	@SuppressWarnings("deprecation")
	@Path("/add")
	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public void add(@Context HttpServletRequest request, @Context HttpServletResponse response, @FormParam("name") String name,@FormParam("Image_Url") File file) {
		// upload image
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
		BlobKey blobKey = blobs.get("Image_Url");
		String key_image = blobKey.getKeyString();
		CategoryModel model=new CategoryModel();
		int port =request.getServerPort();
		String host;
		if(port==80){
			host=	request.getServerName();
		}else{
			host=	request.getServerName()+":"+port;
		}
		try {
			Category category=BeanBase.RequestToObject(request, Category.class);
			category.setId(3);
			category.setKey_image(key_image);
			category.setImage_Url(request.getScheme()+"://"+host+"/imageview?image_url="+key_image);
			category.setDelete(1);
			model.add(category);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
